<template>
  <el-container>
    <el-main style="width:100%; padding:0">
      <el-table
        :data="homeworkTable"
        border
        :header-cell-style="{
          background: '#94AFCC',
          color: '#333333',
          padding: '0',
          height: '35px',
          fontSize: '13px',
          textAlign: 'center',
          fontWeight: '700',
        }"
        :highlight-current-row="true"
        :cell-style="{
          padding: '0px',
          textAlign: 'center',
          fontSize: '12px',
          height: '30px',
          color: '#333333',
        }"
        :row-style="{ height: '25px', padding: '0px' }"
      >
        <el-table-column
          prop="homeworkTitle"
          label="课程作业名称"
          :resizable="false"
          width="150"
        ></el-table-column>
        <el-table-column
          prop="homeworkContent"
          label="作业要求"
          :resizable="false"
          width="230"
        ></el-table-column>
        <el-table-column
          prop="score"
          label="分数"
          :resizable="false"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="isCheck"
          label="提交情况"
          :resizable="false"
          width="140"
        ></el-table-column>
        <el-table-column
          prop="publishTime"
          label="发布日期"
          :resizable="false"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="deadline"
          label="截止日期"
          :resizable="false"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="majorName"
          label="具体内容"
          :resizable="false"
          width="100"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="viewConcreteContent(scope.row)"
              class="tableBtn"
              >详情</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="提交作业" :resizable="false" width="150">
          <template slot-scope="scope">
            <!-- <el-upload
              :limit="1"
              action
              :before-upload="beforeAvatarUpload"
              :http-request="upLoad"
              :show-file-list="false"
            >
              <el-button type="text" @click="submitHomework(scope.row)" class="tableBtn">提交</el-button>
            </el-upload>-->
            <el-button
              type="text"
              @click="submitHomework(scope.row)"
              class="tableBtn"
              v-if="Date.parse(scope.row.deadline) > new Date()"
              >提交</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="majorName" label="批改结果" :resizable="false">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="viewCorrection(scope.row)"
              class="tableBtn"
              >查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-dialog
      title="提交课程作业"
      :visible.sync="dialogVisible"
      width="1000px"
      :before-close="handleClose"
      :close-on-click-modal="false"
      center
    >
      <el-main class="publishTable" style="padding:10px 40px">
        <el-form label-width="120px">
          <el-row>
            <el-col :span="13">
              <el-form-item label="课程作业名称">
                <el-input
                  placeholder="请输入作业标题"
                  v-model="currentHomework.homeworkTitle"
                  :readonly="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="截止日期" :readonly="true">
                <el-input
                  v-model="currentHomework.deadline"
                  :readonly="true"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="回答内容">
                <el-input
                  type="textarea"
                  placeholder="请输入回答内容"
                  v-model="fileInfo.answerContent"
                  resize="none"
                  style="margin-top:12px"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-divider></el-divider>
        <el-form label-width="120px" style="margin-top:20px">
          <el-form-item label="相关附件">
            <input id="fileSelector" type="file" name="filename" />
          </el-form-item>
        </el-form>
        <div style="text-align:center;margin-top:20px; height:50px">
          <el-button class="publishBtn" @click="upLoad">提交课程作业</el-button>
        </div>
      </el-main>
      <div v-if="submiting">
        <div>文件上传进度</div>
        <el-progress :percentage="progress"></el-progress>
      </div>
    </el-dialog>
    <el-dialog
      title="课程作业具体内容"
      :visible.sync="dialogVisible2"
      width="1000px"
      :close-on-click-modal="false"
      center
    >
      <el-main class="publishTable" style="padding:10px 40px">
        <el-form label-width="120px">
          <el-row>
            <el-col :span="13">
              <el-form-item label="课程作业名称">
                <el-input
                  placeholder="请输入作业标题"
                  v-model="currentHomework.homeworkTitle"
                  :readonly="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="截止日期" :readonly="true">
                <el-input
                  v-model="currentHomework.deadline"
                  :readonly="true"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="作业要求">
                <el-input
                  type="textarea"
                  v-model="currentHomework.homeworkContent"
                  resize="none"
                  :readonly="true"
                  style="margin-top:12px"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-divider></el-divider>
        <el-form label-width="120px" style="margin-top:20px">
          <el-form-item label="相关附件">
            <a :href="currentHomework.homeworkAttachmentList[0].link">{{
              currentHomework.homeworkAttachmentList[0].attachmentTitle
            }}</a>
          </el-form-item>
        </el-form>
        <!-- <div style="text-align:center;margin-top:20px; height:50px">
          <el-button class="publishBtn" @click="upLoad">提交课程作业</el-button>
        </div> -->
      </el-main>
      <div v-if="submiting">
        <div>文件上传进度</div>
        <el-progress :percentage="progress"></el-progress>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import COS from "cos-js-sdk-v5";
import $ from "jquery";

export default {
  data() {
    return {
      // 用来标识一节课
      identifier: "1",
      homeworkTable: [
        // {
        //   homeworkTitle: "第十章作业",
        //   homeworkContent: "填空题：第3题",
        //   deadline: "2020-12-11 21:36:00",
        //   publishTime: "2020-11-18 17:52:42",
        //   score: null,
        //   isCheck: "未批改",
        // },
        // {
        //   homeworkTitle: "第十章作业",
        //   homeworkContent: "填空题：第3题",
        //   deadline: "2020-12-11 21:36:00",
        //   publishTime: "2020-11-18 17:52:42",
        //   score: null,
        //   isCheck: "未批改",
        // },
      ],
      currentHomework: {
        homeworkId: "",
        homeworkTitle: "",
        homeworkContent: "",
        deadline: "",
        publishTime: "",
        score: "",
        isCheck: "",
        homeworkAttachmentList: [
          {
            attachmentId: "",
            attachmentTitle: "",
            link: "",
          },
        ],
      },

      // 发送给后端的内容
      fileInfo: {
        // 从currentHomework里面选择
        homeworkId: "",
        studentId: "",
        answerContent: "",
        answerAttachments: [
          {
            attachmentTitle: "",
            // 上传成功后的地址
            link: "",
          },
        ],
      },
      uploadFile: "",

      // 上传进度
      progress: 0,
      // 是否正在上传
      submiting: false,
      // 是否完成发布作业
      havePublished: false,
      // 提交作业弹窗是否可见
      dialogVisible: false,
      // 具体内容弹窗是否可见
      dialogVisible2: false,

      // 是否超过提交作业期限
      isOverdue: [],
    };
  },
  methods: {
    // 加载课程列表
    loadHomeworkList() {
      let options = this.$store.state.temp_courseSections[0];
      options.studentId = this.$store.state.id;
      // console.log(options);
      this.$http
        .post(this.$api.HomeworkqueryWorkListOfS, options)
        .then((resp) => {
          if (resp.success) {
            // console.log(resp.data);
            this.homeworkTable = resp.data;
          } else {
            this.$handleFailResp(this, resp);
          }
        });
    },

    // 提交前获取文件的相关信息
    // beforeAvatarUpload(file) {
    //   this.uploadFile = file;
    //   this.fileInfo.answerAttachments[0].attachmentTitle = file.name;
    //   return file.name;
    // },

    // 选择附件
    select() {
      // 获取上传文件的信息
      console.log(document.getElementById("fileSelector").files[0] == null);
      if (document.getElementById("fileSelector").files[0] != null) {
        this.uploadFile = document.getElementById("fileSelector").files[0];
        this.fileInfo.answerAttachments[0].attachmentTitle = this.uploadFile.name;
      }
    },

    // 点击"提交作业"中的提交事件
    submitHomework(val) {
      // 点击弹出弹框
      this.dialogVisible = true;
      console.log(val);
      // 在这里获取那一行的信息并填入currentHomework里面
      this.currentHomework.homeworkId = val.homeworkId;
      this.currentHomework.homeworkTitle = val.homeworkTitle;
      this.currentHomework.homeworkContent = val.homeworkContent;
      this.currentHomework.deadline = val.deadline;
      this.currentHomework.publishTime = val.publishTime;
      this.currentHomework.score = val.score;
      this.currentHomework.isCheck = val.isCheck;
      // this.currentHomework = val
      // 这里是向后端请求是所需信息赋值，详细见接口文档“提交作业”
      this.fileInfo.homeworkId = val.homeworkId;
      this.fileInfo.studentId = this.$store.state.id;
    },

    //提交作业接口
    submitHomeworkApi() {
      let options = this.fileInfo;
      console.log(options);
      this.$http.post(this.$api.HomeworksendingWork, options).then((resp) => {
        if (resp.success) {
          this.$message({
            message: "作业提交成功",
            type: "success",
          });
        } else {
          this.$handleFailResp(this, resp);
        }
      });
    },

    upLoad() {
      // 调用select函数获取文件信息
      this.select();
      console.log("uploadFile");
      console.log(this.uploadFile);
      console.log(this.uploadFile == "");
      var that = this;

      // 弹出提示框询问是否确认提交
      this.$confirm("确认发布作业吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // console.log(this.uploadFile == "")
          if (that.uploadFile == "") {
            // 没有附件，像后端发请求，详细见接口文档“发布作业”
            that.submitHomeworkApi();
            that.havePublished = true;
          } else {
            console.log("上传文件");

            // 身份认证
            var cos = this.getCOS();
            that.submiting = true;
            cos.putObject(
              {
                Bucket: "mybucket-1304114494",
                Region: "ap-guangzhou",
                // 唯一标识文件的key：前面为文件夹，后面为文件名
                Key:
                  that.identifier +
                  "/studentSubmitAttachment/" +
                  "/" +
                  that.currentHomework.homeworkTitle +
                  "/" +
                  that.uploadFile.name,
                StorageClass: "STANDARD",
                Body: that.uploadFile, // 上传文件对象
                // 进度回调函数
                onProgress: function(progressData) {
                  console.log(progressData.percent);
                  // 更新显示进度条
                  that.progress = progressData.percent * 100;

                  // progressData.total 整个文件的大小
                  // progressData.loaded 已上传文件内容大小， progressData.speed 上传文件速度， progressData.percent 上传文件百分百
                  //console.log(progressData.total);
                },
              },
              function(err, data) {
                // 这里是打印文件的保存路径
                console.log(data);

                if (err) {
                  that.$message.error("作业发布失败");
                } else {
                  // 提示上传成功
                  // 向后端发请求
                  // 记录信息, 参见接口
                  var url = "https://";
                  var address = data.Location;
                  that.fileInfo.answerAttachments[0].link = url + address;
                  that.submitHomeworkApi();

                  that.havePublished = true;
                }
              }
            );
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消发布",
          });
        });
    },

    // 身份认证
    getCOS() {
      var cos = new COS({
        AppId: "1304114494",
        SecretId: "AKIDwhU5nHLegU7C5rloQmslkVZOyRgrElU4",
        SecretKey: "d5SdcLMI7IKHzUxDEIAbstnTfIvsa3HJ",
      });
      return cos;
    },

    // 查看批改结果
    viewCorrection(item) {
      // 获取该行信息，连接口
      console.log(item);
      this.$router.push({
        path: "/student/courseHomework/viewCorrection",
        query: { homeworkId: item.homeworkId },
      });
    },

    // 是否取消上传
    handleClose(done) {
      if (this.havePublished == false) {
        this.$confirm("取消提交作业？")
          .then((_) => {
            this.reset();
            done();
          })
          .catch((_) => {});
      } else {
        this.reset();
        done();
      }
    },

    // 重置状态
    reset() {
      console.log("重置ing");
      this.submiting = false;
      this.fileInfo.homeworkId = "";
      this.fileInfo.studentId = "";
      this.fileInfo.answerContent = "";
      this.fileInfo.answerAttachments[0].attachmentTitle = "";
      this.fileInfo.answerAttachments[0].link = "";
      this.havePublished = false;
      // 清空input里面的文件
      var obj = document.getElementById("fileSelector");
      obj.outerHTML = obj.outerHTML;
    },

    // 点击表头具体内容-详情 查看作业具体内容
    viewConcreteContent(item) {
      // 这里接接口，具体看接口文档“查看单个作业（学生）”
      let options = {
        homeworkId: item.homeworkId,
        studentId: this.$store.state.id,
      };
      console.log(options);
      this.$http
        .post(this.$api.HomeworkqueryWorkConditionOfS, options)
        .then((resp) => {
          if (resp.success) {
            console.log("single homework");
            console.log(resp.data);
            this.currentHomework = resp.data;
            console.log(this.currentHomework);

            // 弹出弹窗
            this.dialogVisible2 = true;
          } else {
            this.$handleFailResp(this, resp);
          }
        });

      // 获取了相关的附件信息
      // 我这里假装获取了，狗杰不许笑！
      // this.currentHomework.homeworkAttachmentList[0].attachmentTitle =
      //   "测试文档";
      // this.currentHomework.homeworkAttachmentList[0].link =
      //   "https://mybucket-1304114494.cos.ap-guangzhou.myqcloud.com/%E5%BA%A7%E4%BD%8D%E8%A1%A8.xlsx";
      // 更新当前学生信息

      // this.currentHomework.homeworkId = item.homeworkId;
      // this.currentHomework.homeworkTitle = item.homeworkTitle;
      // this.currentHomework.deadline = item.deadline;
      // this.currentHomework.homeworkContent = item.homeworkContent;

      // 更新当前学生信息
    },
  },
  mounted() {
    // 在mounted时调用接口
    // 刷新作业列表
    this.loadHomeworkList();
    this.identifier = this.$store.state.identifier;

    // 详细见接口文档“查询课程作业列表（学生）”
  },
};
</script>

<style lang="less" scoped>
/deep/ .el-input--small .el-input__inner {
  border-radius: 0;
  border: 1px solid #333333;
  color: #333333;
  height: 27px;
  font-size: 13px;
  width: 200px;
}

/deep/ .el-form-item__label {
  font-size: 14px;
  color: #333333;
  text-align: left;
}

.el-col-12 {
  height: 50px;
}

.el-divider {
  height: 2px;
  width: 90%;
  margin: auto;
}

/deep/ .el-dialog__title {
  font-size: 23px;
  color: rgb(51, 55, 68);
}

/deep/ .el-dialog--center .el-dialog__body {
  padding: 25px 25px 0px;
}

/deep/ .el-input {
  width: 260px;
}

/deep/ .el-input__inner {
  border-radius: 0;
  height: 30px;
  border: 1px solid rgb(153, 153, 153);
  font-size: 13px;
}

/deep/ .el-form-item__label {
  color: #333333;
  font-size: 15px;
  text-align: left;
}

/deep/ .el-textarea__inner {
  width: 400px;
  height: 200px;
  border-radius: 0;
  border: 1px solid rgb(153, 153, 153);
}

// 提交作业按钮
.publishBtn {
  margin: auto;
  background-color: rgb(89, 136, 179);

  color: #f2f2f2;
}

// 表格里面的按钮
.tableBtn {
  font-size: 13px;
  color: #797979;
}
</style>
